<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "yyh_patient".
 *
 * @property int $id
 * @property string $name 姓名
 * @property string|null $sex 性别
 * @property int|null $age 年龄
 * @property string|null $address 地址
 * @property string $telphone 电话
 * @property string $istoday 是否现场
 * @property int $department_id 科室
 * @property string $disease_ids 病种
 * @property string|null $order_number 预约号
 * @property string|null $qq QQ
 * @property string|null $wechat 微信
 * @property string $worktime 咨询班次
 * @property int $communication_id 咨询途径
 * @property int $comeway_id 媒体来源
 * @property int $user_id 咨询人员
 * @property string $createtime 录入时间
 * @property string $status 状态
 * @property int|null $order_doctor_id 预约医生
 * @property int|null $operate_doctor_id 接诊医生
 * @property string|null $order_time 预约时间
 * @property string|null $arrive_time 到诊时间
 * @property string|null $forever_id 永久身份
 * @property string|null $keyword 搜索关键词
 * @property string|null $last_recall_time 回访信息
 * @property string|null $condition_log 病情备注
 * @property string|null $talk_log 聊天记录
 * @property string|null $edit_log 编辑记录
 */
class Patient extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'yyh_patient';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name', 'telphone', 'department_id', 'disease_ids', 'communication_id', 'comeway_id', 'user_id', 'createtime', 'status', 'forever_id'], 'required'],
            [['sex', 'istoday', 'status', 'condition_log', 'talk_log', 'edit_log'], 'string'],
            [['age', 'department_id', 'communication_id', 'comeway_id', 'user_id', 'order_doctor_id', 'operate_doctor_id'], 'integer'],
            [['createtime', 'order_time', 'arrive_time', 'last_recall_time'], 'safe'],
            [['name', 'telphone', 'order_number', 'qq'], 'string', 'max' => 32],
            [['address', 'disease_ids'], 'string', 'max' => 128],
            [['wechat', 'forever_id', 'keyword'], 'string', 'max' => 64],
            [['workgroup'], 'string', 'max' => 64],
            //['order_number', 'unique', 'message' => '咨询人员的预约号，不能重复'],
            ["telphone", function ($attr, $params) {
                if (trim($this->$attr) == $this->getOldAttribute($attr)) {
                    return true;
                } else if (strlen(trim($this->$attr)) == 11) { //通过电话号码相同的患者，需要在系统设置的时间间隔（天）以后，才能被再次录入。
                    $number = trim($this->$attr);
                    $patient_list = Patient::find()->where("telphone = '{$number}'")->orderBy('createtime')->all();
                    $validate_after_between_date = false;
                    $between_date = Sysconfig::get_var_value('global_first_between_date');
                    if (null != $patient_list && count($patient_list) > 0) {
                        if (date($patient_list[0]->createtime) > date('Y-m-d', strtotime('-' . $between_date . ' day'))) {
                            $validate_after_between_date = true;
                        }
                        $error_string = "";
                        foreach ($patient_list as $p) {
                            $error_string .= '咨询：' . $p->username . ' 于' . $p->createtime . '已经添加过该电话号码；';
                        }
                    }
                    if ($validate_after_between_date) {
                        $this->addError("电话号码", "输入的电话号码重复。系统设定，同一个电话号码的患者，必须在" . $between_date . "天后才能再次录入系统。" . $error_string);
                    } else {
                        return true;
                    }
                } else if (strlen(trim($this->$attr)) < 2 && (!empty(trim($this->qq)) || !empty(trim($this->wechat)))) {
                    return true;
                } else {
                    $this->addError("电话号码", "输入的电话号码有误。如果不知道患者手机号码或者座机号码，就填写 1，但 微信 或 QQ 其中一项必须填写。");
                }
            }],
            ["forever_id", function ($attr, $params) {
                if (preg_match('/([0-9]|[a-f]|[A-F]){32}/', trim($this->$attr))) {
                    return true;
                } else if (strpos($this->$attr, '等') !== false || strpos($this->$attr, '待') !== false) {
                    return true;
                } else {
                    $this->addError("永久身份", "永久身份是32位商务通字符串，如果不知道患者的永久身份，请填：没找到，等待竞价填写");
                }
            }],
            ["age", function ($attr, $params) {
                if ((int)($this->$attr) < 1 || (int)(trim($this->$attr)) > 99) {
                    $this->addError("年龄", "患者年龄应该在1至99岁。小于1岁，大于99岁的患者，我们医院一般不接");
                } else {
                    return true;
                }
            }],
            ["order_time", function ($attr, $params) {
                if (trim($this->$attr) == null || empty(trim($this->$attr))) {
                    return true;
                } else if (trim($this->$attr) == $this->getOldAttribute($attr)) {
                    return true;
                } else if (date($this->$attr) > date('Y-m-d H:i:00') && date($this->$attr) < date('Y-m-d H:i:s', strtotime('+3 month'))) {
                    return true;
                } else {
                    $this->addError("预约时间", "患者预约的来院时间，必须在当前时间" . date('H:i:s') . "以后，且在3个月以内。");
                }
            }],
            ["disease_ids", function ($attr, $params) { //验证病种是否属于科室,医生是否属于科室
                if (Department::validate_disease($this->department_id, $this->$attr)) {
                    return true;
                }
                $this->addError("预约病种", "您为患者预约的病种不属于选择的科室。");
            }],
            ["order_doctor_id", function ($attr, $params) { //验证病种是否属于科室,医生是否属于科室
                if (Department::validate_doctor($this->department_id, $this->$attr)) {
                    return true;
                }
                $this->addError("预约医生", "您为患者预约的医生不属于选择的科室。");
            }],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '姓名',
            'sex' => '性别',
            'age' => '年龄',
            'address' => '地址',
            'telphone' => '电话',
            'istoday' => '是否现场',
            'department_id' => '科室',
            'disease_ids' => '病种',
            'order_number' => '预约号',
            'qq' => 'QQ',
            'wechat' => '微信',
            'workgroup' => '咨询班次',
            'communication_id' => '咨询途径',
            'comeway_id' => '媒体来源',
            'user_id' => '咨询人员',
            'createtime' => '录入时间',
            'status' => '状态',
            'order_doctor_id' => '预约医生',
            'operate_doctor_id' => '接诊医生',
            'order_time' => '预约时间',
            'arrive_time' => '到诊时间',
            'forever_id' => '永久身份',
            'keyword' => '搜索关键词',
            'last_recall_time' => '最后回访时间',
            'condition_log' => '病情备注',
            'talk_log' => '聊天记录',
            'edit_log' => '编辑记录',
        ];
    }

    public function getUsername()
    {
        if (null != $this->user_id) {
            return User::find()->where("id = {$this->user_id}")->one()->showname;
        }
        return null;
    }

    public function getDepartment_name()
    {
        if (null != $this->department_id) {
            return Department::find()->where("id = {$this->department_id}")->one()->name;
        }
        return null;
    }

    public function getDisease_name()
    {
        if (null != $this->disease_ids) {
            if (strpos($this->disease_ids, ',') !== false) {
                $rs = Disease::find()->where("id in ({$this->disease_ids})")->all();
                $disease_array = [];
                foreach ($rs as $p) {
                    $disease_array[] = $p->name;
                }
                return implode(',', $disease_array);
            } else {
                return Disease::find()->where("id = {$this->disease_ids}")->one()->name;
            }
        }
        return null;
    }

    public function getComeway_name()
    {
        if (null != $this->comeway_id) {
            return Comeway::find()->where("id = {$this->comeway_id}")->one()->name;
        }
        return null;
    }

    public function getCommunication_name()
    {
        if (null != $this->communication_id) {
            return Communication::find()->where("id = {$this->communication_id}")->one()->name;
        }
        return null;
    }

    public function getOrder_doctor_name()
    {
        if (null != $this->order_doctor_id) {
            return Doctor::find()->where("id = {$this->order_doctor_id}")->one()->name;
        }
        return null;
    }

    public function getOperate_doctor_name()
    {
        if (null != $this->operate_doctor_id) {
            return Doctor::find()->where("id = {$this->operate_doctor_id}")->one()->name;
        }
        return null;
    }

    public function getRecalls()
    {
        if (null != $this->id) {
            return Recall::find()->where("id = {$this->id}")->all();
        }
        return null;
    }

    public function getFilter_phone()
    {
        if ('隐藏部分' == Yii::$app->user->identity->jobModel->check_patient_power(1) && strlen($this->telphone) > 8) {

            return substr($this->telphone, 0, 3) . '****' . substr($this->telphone, 7, 4);
        }
        return $this->telphone;
    }

    private static function sql($sql)
    {
        $command = Yii::$app->getDb()->createCommand($sql);
        return $command->queryAll();
    }
}
